package com.example.anquan.Service;

import com.example.anquan.guanli.Article;
import com.example.anquan.guanli.Comment;
import com.example.anquan.guanli.User;
import com.example.anquan.repository.RoleRepository;
import com.example.anquan.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class UserService implements UserDetailsService {

@Autowired
    UserRepository userRepository;

        @Override
        public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
                User user = userRepository.findByUsername(s);
                if(user == null){
                        throw new UsernameNotFoundException("用户不存在");
                }
                return user;
        }

    public List<User> findAll() {
        return userRepository.findAll();
    }


    @Autowired
    private RoleRepository roleRepository;
    public boolean register(String username, String password) {
        if (userRepository.findByUsername(username) != null) {
            return false;
        } else {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            User user = new User();
            user.setUsername(username);
            user.setPassword(encoder.encode(password));
            user.setRoles(Arrays.asList(roleRepository.findById(2).get()));
            user.setDate(new Date());
            userRepository.save(user);
            return true;
        }
    }
        }
